import React, { useEffect, useRef } from 'react';
import * as echarts from 'echarts/core';
import {
  GridComponent,
  TooltipComponent,
  LegendComponent,
  DataZoomComponent,
} from 'echarts/components';
import { LineChart as _LineChart } from 'echarts/charts';
import { UniversalTransition } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';

echarts.use([
  GridComponent,
  TooltipComponent,
  LegendComponent,
  _LineChart,
  CanvasRenderer,
  UniversalTransition,
  DataZoomComponent,
]);

const LineChart: React.FC<any> = ({ xAxis, series, bottom = 25, name, width = 560 }) => {
  const chartRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (chartRef.current && xAxis) {
      const chartInstance = echarts.init(chartRef.current);

      series[0] = {
        ...series[0],
        areaStyle: {
          opacity: 0.1,
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 1,
              color: '#fff',
            },
            {
              offset: 0,
              color: '#1890ff',
            },
          ]),
        },
      };

      const option: echarts.EChartsCoreOption = {
        tooltip: {
          trigger: 'axis',
          confine: true,
        },
        legend: {
          icon: 'rect',
          itemHeight: 3,
          itemWidth: 10,
          orient: 'vertical',
          bottom: 0,
          left: 0,
        },
        grid: {
          left: 10,
          right: 24,
          top: 10,
          bottom,
          containLabel: true, // 如果有需要包含坐标轴标签，可以设置此项
        },
        color: ['#1890ff', '#ff922e'],
        dataZoom: [
          {
            type: 'inside', // 支持内部鼠标滚动平移
            zoomOnMouseWheel: true, // 关闭滚轮缩放
            moveOnMouseMove: true, // 鼠标移动能触发数据窗口平移
          },
        ],
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: xAxis,
          axisLine: {
            lineStyle: {
              color: '#e8e8e8', // 轴线颜色
            },
          },
          axisLabel: {
            show: true, // 显示标签
            textStyle: {
              color: '#0009', // 文字颜色
            },
          },
          axisTick: {
            show: false,
          },
        },
        yAxis: {
          type: 'value',
          name,
          splitLine: {
            lineStyle: {
              type: 'dashed',
            },
          },
        },
        series: series.map(item => ({
          ...item,
          showSymbol: item?.data?.length === 1,
        })),
      };

      chartInstance.setOption(option);

      return () => {
        chartInstance.dispose();
      };
    }

    return;
  }, [chartRef.current, xAxis]);

  return <div ref={chartRef} style={{ width, height: 215 }} />;
};

export default LineChart;
